<template>
  <div>
    <!-- 页面标题 -->
    <v-row class="mb-6">
      <v-col cols="12" class="d-flex justify-between align-center">
        <div>
          <h2 class="text-h4 font-weight-bold">校车离园名单</h2>
          <p class="text-subtitle-1 text-medium-emphasis mt-1">查看今日分配到本校车的离园学生</p>
        </div>
        <div class="d-flex align-center">
          <v-chip :color="timeColor" variant="elevated" class="me-3">
            {{ formattedTime }}
          </v-chip>
          <v-btn color="success" prepend-icon="mdi-download" @click="exportList" variant="outlined">
            导出名单
          </v-btn>
        </div>
      </v-col>
    </v-row>



    <!-- 学生列表 -->
    <v-row>
      <v-col cols="12">
        <v-card>
          <v-card-title class="d-flex justify-between align-center">
            <div>
              <v-icon class="me-2">mdi-format-list-bulleted</v-icon>
              学生详细名单
            </div>
          </v-card-title>
          <v-card-text>
            <!-- 加载状态 -->
            <div v-if="studentsStore.loading" class="text-center py-8">
              <v-progress-circular indeterminate color="primary"></v-progress-circular>
              <div class="mt-2">加载中...</div>
            </div>

            <!-- 学生表格 -->
            <div v-else-if="filteredStudents.length > 0">
              <v-data-table
                :headers="tableHeaders"
                :items="filteredStudents"
                :items-per-page="10"
                class="elevation-1"
              >
              </v-data-table>
            </div>

            <!-- 无数据提示 -->
            <div v-else class="text-center py-8">
              <v-icon size="64" color="grey-lighten-1" class="mb-4">mdi-account-off</v-icon>
              <div class="text-h6 text-medium-emphasis">暂无校车离园学生</div>
              <div class="text-body-2 text-medium-emphasis mt-2">今日还没有学生被分配到本校车离园</div>
            </div>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useStudentsStore } from '@/stores/students'

const authStore = useAuthStore()
const studentsStore = useStudentsStore()

// 响应式数据
const currentTime = ref(new Date())

// 表格头部定义
const tableHeaders = ref([
  { title: '姓名', key: 'student_name', sortable: true },
  { title: '学号', key: 'student_no', sortable: true },
  { title: '班级', key: 'class_name', sortable: true }
])

// 计算属性
const filteredStudents = computed(() => {
  return studentsStore.students || []
})



const timeColor = computed(() => {
  const hour = currentTime.value.getHours()
  if (hour >= 14 && hour < 16) return 'success'
  if (hour >= 16 && hour < 18) return 'warning'
  return 'primary'
})

const formattedTime = computed(() => {
  return currentTime.value.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
})

// 方法
const loadDepartureList = async () => {
  try {
    await studentsStore.fetchDepartureStudents()
  } catch (error) {
    console.error('加载离园名单失败:', error)
    window.showNotification?.('加载离园名单失败', 'error')
  }
}

const exportList = () => {
  const XLSX = window.XLSX
  if (!XLSX) {
    window.showNotification?.('XLSX库未加载，请刷新页面重试', 'error')
    return
  }

  const xlsxData = [
    ['学生姓名', '学号', '班级'],
    ...studentsStore.students.map(student => [
      student.student_name,
      student.student_no,
      student.class_name
    ])
  ]

  const ws = XLSX.utils.aoa_to_sheet(xlsxData)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '校车离园名单')
  XLSX.writeFile(wb, `校车离园名单_${new Date().toISOString().split('T')[0]}.xlsx`)

  window.showNotification?.('离园名单导出成功', 'success')
}



const updateCurrentTime = () => {
  currentTime.value = new Date()
}

// 生命周期
onMounted(() => {
  loadDepartureList()
  updateCurrentTime()

  // 每秒更新时间
  const timeInterval = setInterval(updateCurrentTime, 1000)

  // 每5分钟自动刷新列表
  const refreshInterval = setInterval(loadDepartureList, 5 * 60 * 1000)

  // 清理定时器
  onUnmounted(() => {
    clearInterval(timeInterval)
    clearInterval(refreshInterval)
  })
})
</script>

<style scoped>
.v-card {
  transition: all 0.3s ease;
}

.v-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.v-alert {
  border-left: 4px solid currentColor;
}

/* 颜色样本样式 */
.color-sample {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  flex-shrink: 0;
}

.color-sample.status-departed {
  background: linear-gradient(135deg, #4CAF50, #66BB6A);
}

.color-sample.status-abnormal {
  background: linear-gradient(135deg, #F44336, #EF5350);
}

.color-sample.status-waiting {
  background: linear-gradient(135deg, #9E9E9E, #BDBDBD);
}
</style>